package me.wangqu.weiyouqu.web.rest;

import me.wangqu.weiyouqu.web.rest.util.UpYunHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

/**
 * Created by arcticfox on 5/13/16.
 */
@RestController
@RequestMapping("/api/file")
public class FileResource {

    private final Logger log = LoggerFactory.getLogger(FileResource.class);

    public static String ROOT = "upload-dir";

    static {
        new File(ROOT).mkdir();
    }


    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/images", method = RequestMethod.POST)
    public ResponseEntity<?> uploadImg(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件为空, 上传失败");
        }
        String filenameExtension = StringUtils.getFilenameExtension(file.getOriginalFilename());
        if (!"JPEG".equalsIgnoreCase(filenameExtension) && !"JPG".equalsIgnoreCase(filenameExtension)
            && !"PNG".equalsIgnoreCase(filenameExtension)) {
            return ResponseEntity.badRequest().body("图片仅支持JPG或PNG格式");
        }
        UUID uuid = UUID.randomUUID();
        String filename = StringUtils.replace(uuid.toString(), "-", "").concat("." + filenameExtension);
        String filePath = ROOT + File.separator + filename;
        File fileLocal = new File(filePath);
        try {
            // 文件保存本地
            BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(fileLocal));
            FileCopyUtils.copy(file.getInputStream(), stream);
            stream.close();
            // 文件上传又拍云
            UpYunHelper helper = new UpYunHelper();
            return ResponseEntity.ok(helper.uploadImage(fileLocal, filename));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("文件上传失败");
        } finally {
            // 删除本地缓存文件
            if (fileLocal != null && fileLocal.exists()) {
                fileLocal.delete();
            }
        }
    }
}
